import 'package:flutter/material.dart';
import 'package:flutter_house_manager/api/home.dart';
import 'package:flutter_house_manager/utils/toast.dart';
import 'package:flutter_html/flutter_html.dart';

class NoticeDetail extends StatefulWidget {
  const NoticeDetail({super.key});

  @override
  State<NoticeDetail> createState() => _NoticeDetailState();
}

class _NoticeDetailState extends State<NoticeDetail> {
  Map<String, dynamic> _announceDetail = {};
  @override
  void initState() {
    super.initState();
    // 从路由参数中获取id
    //final id = ModalRoute.of(context)?.settings.arguments; //从另外一个生命周期获取参数
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    final params =
        ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    if (params != null && params["id"] != null) {
      // 调用前先声明
      getAnnounceDetail(params["id"] as String);
    }
  }

  getAnnounceDetail(String id) async {
    final res = await getAnnounceDetailAPI(id);
    if (res != null) {
      setState(() {
        _announceDetail = res;
      });
    } else {
      PromptAction.showError('获取公告详情失败');
    }
  }

  Widget getBody() {
    return Container(
        padding: const EdgeInsets.all(15),
        child: ListView(
          scrollDirection: Axis.vertical,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _announceDetail["title"] ?? '',
                  style: const TextStyle(
                      fontSize: 24, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      _announceDetail["creatorName"] ?? '',
                      style: const TextStyle(color: Colors.grey, fontSize: 16),
                    ),
                    Text(
                      _announceDetail["createdAt"] ?? '',
                      style: const TextStyle(color: Colors.grey, fontSize: 16),
                    )
                  ],
                ),
                Html(data: _announceDetail["content"] ?? '')
              ],
            ),
          ],
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: const Text(
        '公告详情',
        style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
      )),
      body: getBody(),
    );
  }
}
